package sing.myapp.net.interceptor

import android.os.Looper
import com.alibaba.fastjson.JSON
import com.alibaba.fastjson.JSONObject
import okhttp3.Interceptor
import okhttp3.MediaType
import okhttp3.Response
import okhttp3.ResponseBody
import sing.core.ext.util.loge
import sing.core.ext.util.showShort
import sing.myapp.router.JumpCenter

class MyResponseInterceptor : Interceptor {
//    @Throws(IOException::class)
    override fun intercept(chain: Interceptor.Chain): Response {
        var request = chain.request()
        request.url().url().path.loge("http start -> : ")
        val requestBuilder = request.newBuilder()
        request = requestBuilder.build()
        try {
            val response = chain.proceed(request)
            val responseBody = response.body()
            var contentType: MediaType? = null
            if (responseBody != null) {
                contentType = responseBody.contentType()
            }
            var subtype: String? = null
            val body: ResponseBody
            if (contentType != null) {
                subtype = contentType.subtype()
            }
            return if (subtype != null && (subtype.contains("json")
                        || subtype.contains("xml")
                        || subtype.contains("plain")
                        || subtype.contains("html"))) {
                var bodyString = responseBody!!.string()
                val obj = JSON.parseObject(bodyString)
                val code = obj.getInteger("code")
//                if (request.url().url().toString().contains("setPhoneZMF")){ // 保存芝麻分
//                    val o = JSONObject()
//                    o["code"] = code
//                    o["message"] = obj.getString("message")
//                    val data = JSONObject()
//                    data["url"] = obj.getString("url")
//                    data["ed"] = obj.getString("ed")
//                    o["data"] = data
//                    bodyString = o.toJSONString()
//                }
                request.url().url().path.loge("http end -> : ")
                body = ResponseBody.create(contentType, bodyString)

                when (code) {
                    406 -> { // 登录失效？
                        JumpCenter.toLogin()
                        Looper.prepare()
                        obj.getString("msg").showShort()
                        Looper.loop()
                        Looper.myLooper()
                    }
                }
                response.newBuilder().body(body).build()
            } else {
                response
            }
        } catch (e: Exception) {
            val temp = e.message
            if (temp != null && temp.contains("Failed")) {
                Looper.prepare()
                "请检查网络".showShort()
                Looper.loop()
                Looper.myLooper()
            }
        }
        return chain.proceed(request)
    }
}